<template>
  <el-tabs
    v-model="editableTabsValue"
    type="card"
    class="demo-tabs"
    closable
    @tab-remove="removeTab"
    @tab-click="clickBtn"
  >
    <el-tab-pane
      v-for="item in tabsList"
      :key="item.path"
      :label="$t(`menus.${item.chang}`)"
      :name="item.path"
    >
    </el-tab-pane>
  </el-tabs>
</template>

<script lang='ts' setup>
import { computed, onMounted, ref, watch } from "vue";
import { useRoute,useRouter } from "vue-router";
import { useStore } from "../../store/index";
import { ITabe } from "../../store/type/index";
const store = useStore();
const router = useRouter();
const route = useRoute();
//通过计算属性获取tabs数据
const tabsList = computed(() => {
  return store.getters["getTabs"];
});
const editableTabsValue = ref("");
const srtActiveTab = () => {
  editableTabsValue.value = route.path;
};
//删除选项卡
const removeTab = (targetName: string) => {
  //首页不删除
  if(targetName === '/dashboard') return;
  const tabs = tabsList.value
  let activeName = editableTabsValue.value
  if (activeName === targetName) {
    tabs.forEach((tab:ITabe, index:number) => {
      if (tab.path === targetName) {
        const nextTab = tabs[index + 1] || tabs[index - 1]
        if (nextTab) {
          activeName = nextTab.path
        }
      }
    })
  }
  editableTabsValue.value = activeName
  store.state.tabsList = tabs.filter((tab:ITabe) => tab.path !== targetName)
  //跳转路由
  router.push({path:activeName})
}
//添加选项卡
const addTab = () => {
  //从当前路由 获取path和title
  const { path, meta } = route;
  //通过vuex设置
  const tab: ITabe = {
    path: path,
    title: meta.title as string,
    chang: meta.chang as string,
  };
  store.commit("addTabe", tab);
};
watch(
  () => route.path,
  () => {
    srtActiveTab();
    addTab();
  }
);
//解决数据丢失问题
const beforRefresh =  () =>{
  window.addEventListener("beforeunload",()=>{
    sessionStorage.setItem('tabsView',JSON.stringify(tabsList.value))
  })
  let tabSession = sessionStorage.getItem('tabsView')
  if(tabSession){
    let oldTabs = JSON.parse(tabSession)
    if(oldTabs.length>0){
      store.state.tabsList = oldTabs
    }
  }
}
//初始
onMounted(()=>{
  beforRefresh();
  srtActiveTab();
    addTab();
})
//选项卡点击事件
const clickBtn = (tab:any)=>{
  const { props } = tab;
  //跳转路由
  router.push({path:props.name})
}
</script>

<style lang="scss" scoped>
</style>